package cn.edu.scnu.semart.goods.service.Impl;

import cn.edu.scnu.semart.goods.service.ImageService;
import cn.edu.scnu.semart.common.utils.ImageUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class ImageServiceImpl implements ImageService {

//    图片上传目录
    private static final String IMAGE_UPLOAD_DIR = "D:/uploads/";//测试用路径


    @Override
    public String uploadAndCompressImage(MultipartFile image) throws IOException {
        // 保存原始图片
        File originalFile = new File(IMAGE_UPLOAD_DIR + image.getOriginalFilename());
        image.transferTo(originalFile);

        // 压缩图片
        File compressedFile = new File(IMAGE_UPLOAD_DIR + "compressed_" + image.getOriginalFilename());
        ImageUtil.compressImage(originalFile, compressedFile, 800, 800); // 设置压缩后的宽高

        // 删除原始图片，只保留压缩后的图片
        if (originalFile.exists()) {
            originalFile.delete();  // 删除原始图片
        }

        return "图片上传并压缩成功，压缩图片路径：" + compressedFile.getAbsolutePath();
    }

    @Override
    public File downloadCompressedImage(String imageName) throws IOException {
        // 查找压缩后的图片
        File compressedFile = new File(IMAGE_UPLOAD_DIR + "compressed_" + imageName);

        // 如果压缩图片不存在，直接返回原图片（不进行压缩）
        if (!compressedFile.exists()) {
            File originalFile = new File(IMAGE_UPLOAD_DIR + imageName);
            if (originalFile.exists()) {
                // 压缩原始图片并保存为压缩文件
                ImageUtil.compressImage(originalFile, compressedFile, 800, 800); // 压缩图片
            } else {
                throw new IOException("图片文件未找到：" + imageName);
            }
        }

        return compressedFile;  // 直接返回已压缩的图片文件
    }
}